package com.xh.jf_blog.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.xh.jf_blog.common.util.R;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author PangJunjie
 * @Date 2024/1/29/029
 */
public class AdminLoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginInfo = request.getSession().getAttribute("loginInfo");
        if (loginInfo == null) {
            /*统一处理中文乱码*/
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            String xRequestedWith = request.getHeader("X-Requested-With");
            if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) {
                response.getWriter().println(JSON.toJSON(R.error(401, "请先登录！")));
            } else {
                response.sendRedirect(request.getContextPath() + "/admin/nologin");
            }
            return false;
        }
        return true;
    }
}
